package com.thwcompany.config;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
 * @program: springboot-rabbit-mq
 * @author: tenghw
 * @create: 2024-01-27 14:21
 * @Version 1.0
 * @description: 延迟队列配置
 **/
@Configuration
public class DelayedQueueConfig {
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";// 延迟队列名称
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";// 延迟交换机名称
    public static final String DELAYED_ROUTING_KEY = "delayed.routingKey";// 延迟队列绑定的路由键

    /**
     *  定义延迟交换机：你无需自定义DelayedMessageExchange类，只需像创建一个具有x-delayed-type属性的DirectExchange即可。
     */
    @Bean("delayedExchange")
    public CustomExchange  delayedExchange(){
        Map<String, Object> args = new HashMap<>();
        // 自定义交换机的类型
        args.put("x-delayed-type", "direct");
        // 此处x-delayed-message指定为延迟交换机
        return new CustomExchange (DELAYED_EXCHANGE_NAME,  "x-delayed-message",true, false, args);
    }

    /**
     *  延迟队列
     */
    @Bean("delayedQueue")
    public Queue delayedQueue(){
        //return new Queue(DELAYED_QUEUE_NAME, true, false, false, arguments);
        return QueueBuilder
                .durable(DELAYED_QUEUE_NAME)//.NonDurable消息非持久化
                //.withArguments(arguments)
                .build();
    }

    /**
     *  绑定
     */
    @Bean
    public Binding bindingDelayedQueue(@Qualifier("delayedQueue") Queue delayedQueue,
                                       @Qualifier("delayedExchange") CustomExchange delayedExchange){
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }
}